<template>
  <div class="input-number">
    <button :disabled="isSubDisabled" class="fl" @click="onSubtract">-</button>
    <input type="text" :value="currentValue" @change="onInputChange">
    <button :disabled="isIncDisabled" class="fr" @click="onIncrease">+</button>
  </div>
</template>

<script>
  export default {
    props: {
      value: {
        type: Number,
        default: 0
      },
      minNum: {
        type: Number,
        default: 0
      },
      maxNum: [Number]
    },
    data() {
      return {
        currentValue: this.value,
        isSubDisabled: false, // 最低的disabled
        isIncDisabled: false // 最高的disabled
      }
    },
    created() {
      if (this.value <= this.minNum) {
        this.isSubDisabled = true
      } else if (this.maxNum && this.value >= this.maxNum) {
        this.isIncDisabled = true
      }
    },
    methods: {
      onSubtract(ev) {
        if (this.currentValue <= 0 || this.currentValue <= this.minNum) return
        this.currentValue--
        this.$emit('input', this.currentValue)
      },
      onIncrease() {
        if (this.maxNum && this.currentValue >= this.maxNum) return
        this.currentValue++
        this.$emit('input', this.currentValue)
      },
      onInputChange(ev) {
        this.currentValue = Number(ev.target.value)
        // 手动更改数值<=0时，则自动还原为之前的数值
        if (this.currentValue <= 0 || isNaN(this.currentValue)) {
          this.currentValue = this.value
          // this.$toast(`最低起订量为${this.value}件`)
        }
        if (this.maxNum && this.currentValue > this.maxNum) {
          this.currentValue = this.maxNum
          this.$toast(`不能超过库存${this.maxNum}件`)
        }
        this.$emit('input', this.currentValue)
      }
    },
    watch: {
      value(newVal, oldVal) {
        this.currentValue = newVal
        this.isSubDisabled = this.currentValue <= this.minNum
        this.isIncDisabled = (this.maxNum && this.currentValue >= this.maxNum)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .input-number {
    display: inline-block;
    width: 120px;
    height: 28px;
    line-height: 28px;
    border: 1px solid #ccc;
    overflow: hidden;
    button {
      width: 30px;
      height: 28px;
      background: #f6f6f6;
      font-size: 20px;
      &.fl {
        border-right: 1px solid #ccc;
      }
      &.fr {
        border-left: 1px solid #ccc;
      }
      &[disabled] {
        background: #eee;
        color: #999;
        cursor: not-allowed;
      }
    }
    input {
      width: 58px;
      height: 28px;
      text-align: center;
    }
  }
</style>